package com.derekandbritt.booST.data;

import java.util.HashMap;
import java.util.List;

import org.opensocial.models.Person;

import com.derekandbritt.booST.endpoints.OpenSocialEndpoint;
import com.derekandbritt.booST.exceptions.DataFormatException;

public class OpenSocialFriendCache {

	private List<Person> friendList;
	private HashMap<String, Person> friendMap = new HashMap<String, Person>();
	private long cachedTime;
	
	public OpenSocialFriendCache() { }
	
	public OpenSocialFriendCache(List<Person> friends) throws DataFormatException {
		updateCache(friends);
	}
	
	public void clearCache() {
	    friendList = null;
	    friendMap.clear();
	    cachedTime = 0;
	}
	
	public void updateCache(List<Person> friends) throws DataFormatException {
		this.friendList = friends;
		this.cachedTime = System.currentTimeMillis();
		this.friendMap.clear();
		for(Person friend : friends)
			this.friendMap.put(OpenSocialEndpoint.getPersonId(friend), friend);
	}
	
	public List<Person> getFriends() {	
		return friendList;
	}	
	
	public boolean containsFriend(String friendId) {
		return friendMap.containsKey(friendId);
	}
	
	public Person getFriend(String friendId) {	
		return friendMap.get(friendId);
	}
	
	public boolean isValid() {
		//TODO pull from preferences 
		//TODO reduce cache time limit when getPersonId is fixed (120000)
		return ((cachedTime + 12000000) > System.currentTimeMillis());
	}
}
